﻿using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Data;
using System.Web.UI.WebControls;
using System.Text;
using Microsoft.SharePoint.Utilities;
using System.Web.UI;

namespace iGRID_Ooredoo_SPCRM_My_Opportunities.Layouts.iGRID_Ooredoo_SPCRM_My_Opportunities
{

    public partial class Opportunity_Actions : LayoutsPageBase
    {
        const string QSTR_ENQUIRYID = "EnquiryId";
        const string SESSION_TBL = "tblEnquiryActions", SESSION_INSERT = "insert", ACTION_ID = "actionId", ENQUIRY_TITLE = "EnquiryTitle";
        string strEnquiryId;
        string strEnquiryTitle;
        public DateTime strOppDate;
        public string ErrorMsgs;

        SPSite site = SPContext.Current.Site;
        SPQuery query;
        SPWeb web;
        DataTable tblEnquiryActions = new DataTable();
        SPList list;
        ExceptionHandler errMsg = new ExceptionHandler();

        string ActionType = null;

        static int deleteitemID { get; set; }
        static int itmeID { get; set; }
        DataTable dtActionDatas;

        bool canView = false; bool canAdd = false; bool canEdit = false; bool canDelete = false;

        string perm { get; set; }

        protected void Page_Load(object sender, EventArgs e)
        {
            hdnSiteURL.Value = SPContext.Current.Site.Url;

            if (UserPermissions())
            {
                lblEmptyText.Visible = false;
                lblEmptyText.Text = "";
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    try
                    {
                        ClientScript.GetPostBackEventReference(this, string.Empty);
                        //strEnquiryId = "1234";
                        strEnquiryId = Request.QueryString["OppID"];
                        strEnquiryTitle = Request.QueryString["OppTitle"];

                        string ReadOnly = Request.QueryString["ReadOnly"];

                        if (ReadOnly == "1")
                        {
                            InvisibleControls();
                            int countcolumns = gvEnquiryActions.Columns.Count;
                            gvEnquiryActions.Columns[countcolumns - 1].Visible = false;
                        }

                        if (strEnquiryId != null)
                        {
                            list = SPContext.Current.Web.Lists.TryGetList("Action Details");

                            query = new SPQuery();
                            //query.Query = "<Where><And><Eq><FieldRef Name='OpportunityID' /><Value Type='Text'>" + strEnquiryId + "</Value></Eq><Eq><FieldRef Name='Status' /><Value Type='Text'>Active</Value></Eq></And></Where>";

                            query.Query = "<Where><And><Eq><FieldRef Name=\"OpportunityID\" /><Value Type=\"Text\">" + strEnquiryId + "</Value></Eq><Eq><FieldRef Name=\"Status\" />" +
                                "<Value Type=\"Text\">Active</Value></Eq></And></Where><OrderBy><FieldRef Name=\"Created\" Ascending=\"False\" /></OrderBy>";

                            SPListItemCollection coll = GetListItemCollection(list, query);

                            //int SdatelocalId = Convert.ToInt32(SPContext.Current.RegionalSettings.LocaleId);
                            //dtcActionDate.LocaleId = SdatelocalId;

                            dtActStDate.SelectedDate = DateTime.Today;
                            dtActEndDate.SelectedDate = DateTime.Today;
                            lblEnquiryIdShow.Text = strEnquiryId;
                            lblEnquiryTitleShow.Text = GetEnquiryTitle(strEnquiryId); // strEnquiryTitle;

                            if (coll != null)
                            {
                                dtActionDatas = CreateEnquiryActionsDataForGrid(coll);
                            }
                            BindDataToGrid(dtActionDatas);
                        }

                        if (ddlActionTypes.Items.Count > 0)
                        {
                            if (!string.IsNullOrEmpty(ddlActionTypes.SelectedItem.Text))
                                ActionType = ddlActionTypes.SelectedItem.Text;
                        }


                        SPList listActionTypes = SPContext.Current.Web.Lists.TryGetList("Action Types");
                        ddlActionTypes.DataSource = listActionTypes.Items;
                        ddlActionTypes.DataValueField = "Id"; // List field holding value!
                        ddlActionTypes.DataTextField = "Title"; // List field holding name to be displayed on page 
                        ddlActionTypes.DataBind();

                        string eventTarget = Request["__EVENTTARGET"] ?? string.Empty;
                        string eventArgument = Request["__EVENTARGUMENT"] ?? string.Empty;
                        switch (eventTarget)
                        {
                            case "MyConfirmationPostBackEventTarget":
                                if (Convert.ToBoolean(eventArgument))
                                {
                                    AfterUserConfirmationHandler();
                                }
                                break;
                        }
                    }
                    catch (Exception ex)
                    {
                        ErrorMsgs = "iGRID_Ooredoo_SPCRM_My_Opportunities :: OppertunitiesActions" + " :: " + "Parent" + " :: " + "PageLoad";
                        errMsg.GenerateExceptionLog(ErrorMsgs, ex.Message, "");
                    }
                });
            }

            else
            {
                if (!canView)
                {
                    divAppPage.Visible = false;
                    divGv.Visible = false;
                    divError.Visible = true;
                    lblEmptyText.Text = "you do not have permission to view Action details";
                }
                else
                {
                    lblEmptyText.Visible = true;
                    lblEmptyText.Text = "Invalid query string";
                }
            }

            if (canView)
                GridDatas();
        }

        private void GridDatas()
        {
            if (gvEnquiryActions.Rows.Count == 0)
            {
                lblEmptyText.Visible = true;
                if (canAdd)
                {
                    lblEmptyText.Text = "There are no items to show.";
                    btnClose.Visible = false;
                }
                else
                {
                    lblEmptyText.Text = "There are no items to show and you do not have permission to add action";
                    if (canAdd)
                        btnClose.Visible = false;
                    else
                        btnClose.Visible = true;
                    //Response.Write("<script language='javascript'>alert('There are no items to show and you do not have permission to add action');window.parent.location.href = window.parent.location.href</script>");
                }
            }
            else
            {
                lblEmptyText.Visible = false;
                lblEmptyText.Text = "";
                btnClose.Visible = false;
            }
        }

        private bool UserPermissions()
        {
            bool qrtString = false;

            perm = Request.QueryString["Perm"];

            if (perm != null)
            {
                if (perm.Contains("1") || perm.Contains("0"))
                {
                    qrtString = true;

                    int len = perm.Length;

                    if (len == 4)
                    {

                        if (Convert.ToString(perm[0]) == "1") canView = true;
                        if (Convert.ToString(perm[1]) == "1") canAdd = true;
                        if (Convert.ToString(perm[2]) == "1") canEdit = true;
                        if (Convert.ToString(perm[3]) == "1") canDelete = true;

                        if (canView)
                        {
                            divGv.Visible = true;

                        }
                        else
                        {
                            qrtString = false;
                            //Response.Write("<script language='javascript'>alert('you do not have permission to view Action details');window.parent.location.href = window.parent.location.href</script>");
                        }

                        if (canAdd)
                        {
                            divAppPage.Visible = true;
                            divGv.Visible = true;
                        }
                        else
                        {
                            divAppPage.Visible = false;
                        }
                        if (canEdit)
                        {
                            divGv.Visible = true;
                            if (canAdd)
                                divAppPage.Visible = true;
                            else
                                divAppPage.Visible = false;
                        }
                    }
                    else
                    {
                        //qrtString = false;
                        //lblEmptyText.Visible = true;
                        //lblEmptyText.Text = "The query string is not well formed";
                        //ErrorMsgs = "iGRID_Ooredoo_SPCRM_My_Opportunities :: OppertunitiesActions" + " :: " + "Parent" + " :: " + "AfterUserConfirmationHandler";
                        //errMsg.GenerateExceptionLog(ErrorMsgs, "The query string is not well formed", "");
                    }
                }

                else
                {
                    qrtString = false;
                }
            }
            else
            {
                qrtString = false;
            }
            return qrtString;
        }

        protected void AfterUserConfirmationHandler()
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                try
                {
                    using (SPSite oSite = new SPSite(SPContext.Current.Site.Url))
                    {
                        using (SPWeb oWeb = oSite.OpenWeb())
                        {
                            SPListItem listItem = oWeb.Lists.TryGetList("Action Details").GetItemById(deleteitemID);

                            string actionBy = Convert.ToString(listItem["ActionBy"]);
                            SPFieldUserValue fldUser = new SPFieldUserValue(oWeb, actionBy);

                            if (fldUser.User.ToString().ToLower() == Convert.ToString(SPContext.Current.Web.CurrentUser).ToLower() || fldUser.LookupValue.ToString().ToLower() == Convert.ToString(SPContext.Current.Web.CurrentUser).ToLower())
                            {
                                //listItem["Status"] = "Inactive";
                                oWeb.AllowUnsafeUpdates = true;
                                listItem.Delete();
                                oWeb.AllowUnsafeUpdates = false;
                                pnlAlert.Controls.Add(new LiteralControl("<script language='javascript'>alert('Action deleted successfully');</script>"));
                                //ClientScript.RegisterClientScriptBlock(GetType(), "Add Actions", "<script>alert('Action deleted successfully')</script>");
                            }
                            else
                            {
                                pnlAlert.Controls.Add(new LiteralControl("<script language='javascript'>alert('Only Action creater can delete!');</script>"));
                                //ClientScript.RegisterClientScriptBlock(GetType(), "Add Actions", "<script>alert('Only owner has delete the action!')</script>");
                            }
                            query = new SPQuery();
                            query.Query = "<Where><And><Eq><FieldRef Name='OpportunityID' /><Value Type='Text'>" + strEnquiryId + "</Value></Eq><Eq><FieldRef Name='Status' /><Value Type='Text'>Active</Value></Eq></And></Where>";
                            SPListItemCollection coll = GetListItemCollection(list, query);
                            if (coll != null)
                            {
                                dtActionDatas = CreateEnquiryActionsDataForGrid(coll);
                                BindDataToGrid(dtActionDatas);
                            }
                        }
                    }
                    ClearControls();
                }
                catch (Exception ex)
                {
                    ErrorMsgs = "iGRID_Ooredoo_SPCRM_My_Opportunities :: OppertunitiesActions" + " :: " + "Parent" + " :: " + "AfterUserConfirmationHandler";
                    errMsg.GenerateExceptionLog(ErrorMsgs, ex.Message, "");
                }
            });
        }

        private string GetEnquiryTitle(string pEnquiryId)
        {
            string oppTitle = "";
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                try
                {
                    SPList listEnquiries = SPContext.Current.Web.Lists.TryGetList("Opportunity General Data");
                    SPQuery query = new SPQuery();
                    query.Query = "<Where><Eq><FieldRef Name='Opportunity_x0020_ID' /><Value Type='Text'>" + strEnquiryId + "</Value></Eq></Where>";

                    SPListItemCollection coll = listEnquiries.GetItems(query);
                    if (coll.Count > 0)
                    {
                        SPListItem enquiry = coll[0];
                        oppTitle = Convert.ToString(coll[0]["Title"]);
                        strOppDate = Convert.ToDateTime(coll[0]["Created"]);
                    }

                }
                catch (Exception ex)
                {
                    ErrorMsgs = "iGRID_Ooredoo_SPCRM_My_Opportunities :: OppertunitiesActions" + " :: " + "Parent" + " :: " + "GetEnquiryTitle";
                    errMsg.GenerateExceptionLog(ErrorMsgs, ex.Message, "");
                }
            });
            return oppTitle;
        }

        public void InvisibleControls()
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                divAppPage.Visible = false;
                //divControls.Visible = false;
                //lblPONo.Visible = false;
                //txtPONo.Visible = false;
                //lblActionType.Visible = false;
                //ddlActionTypes.Visible = false;
                //lblActionDate.Visible = false;
                //dtcActionDate.Visible = false;
                //lblAmountPaid.Visible = false;
                //txtAmountPaid.Visible = false;
                //txtAmountPaidValidator.Enabled = false;
                //regexAmountValidator.Enabled = false;
                //lblRemarks.Visible = false;
                //txtRemarks.Visible = false;
                //btnSave.Visible = false;
                //btnCancel.Visible = false;
            });
        }
        private DataTable GetEnquiryActionsTable()
        {
            return (DataTable)Session[SESSION_TBL];
        }

        private DataTable ConfigureEnquiryActionsTable()
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                tblEnquiryActions.Columns.Add("ID", typeof(int));
                tblEnquiryActions.Columns.Add("Title", typeof(string));
                tblEnquiryActions.Columns.Add("OpportunityID", typeof(string));
                tblEnquiryActions.Columns.Add("Start Date");
                tblEnquiryActions.Columns.Add("End Date");
                tblEnquiryActions.Columns.Add("Action Type", typeof(string));
                tblEnquiryActions.Columns.Add("LastModifiedBy", typeof(string));
                tblEnquiryActions.Columns.Add("LastModifiedOn", typeof(string));
                tblEnquiryActions.Columns.Add("Remarks", typeof(string));
            });

            return tblEnquiryActions;
        }

        private DataTable CreateEnquiryActionsDataForGrid(SPListItemCollection coll)
        {
            SPWeb oWeb = null;


            SPSecurity.RunWithElevatedPrivileges(delegate()
            {

                DataTable temp;
                DataRow drEnquiryActions;
                temp = coll.GetDataTable();
                tblEnquiryActions.Rows.Clear();
                tblEnquiryActions.Columns.Clear();
                tblEnquiryActions = ConfigureEnquiryActionsTable();
                if (temp != null)
                {
                    //foreach (DataRow dr in temp.Rows)
                    foreach (SPListItem dr in coll)
                    {
                        drEnquiryActions = tblEnquiryActions.NewRow();
                        drEnquiryActions["ID"] = Convert.ToInt32(dr["ID"]);
                        drEnquiryActions["Title"] = Convert.ToString(dr["Title"]);
                        drEnquiryActions["OpportunityID"] = dr["OpportunityID"];
                        drEnquiryActions["Start Date"] = Convert.ToDateTime(dr["ActionStartDate"]).ToString("dd/MM/yyyy hh:mm tt");
                        drEnquiryActions["End Date"] = Convert.ToDateTime(dr["ActionEndDate"]).ToString("dd/MM/yyyy hh:mm tt");
                        drEnquiryActions["Action Type"] = dr["ActionType"];
                        string modifiedBy = Convert.ToString(dr["ActionModifiedBy"]);
                        SPFieldUserValue fldUser = new SPFieldUserValue(SPContext.Current.Web, modifiedBy);
                        string user = Convert.ToString(fldUser.LookupValue);

                        if (user != null)
                        {
                            if (user.Contains("#"))
                            {
                                string[] users = user.Split('\\');
                                drEnquiryActions["LastModifiedBy"] = string.IsNullOrEmpty(Convert.ToString(users[1])) ? Convert.ToString(users[0]) : Convert.ToString(users[1]);
                            }
                            else
                            {
                                drEnquiryActions["LastModifiedBy"] = user;
                            }
                        }
                        else
                        {
                            drEnquiryActions["LastModifiedBy"] = "";
                        }
                        drEnquiryActions["LastModifiedOn"] = Convert.ToDateTime(dr["Modified"]).ToString("dd/MM/yyyy hh:mm tt");
                        if (!string.IsNullOrEmpty(Convert.ToString(dr["Remarks"])))
                            drEnquiryActions["Remarks"] = Util.StripHTML(dr["Remarks"].ToString());
                        else
                            drEnquiryActions["Remarks"] = null;
                        tblEnquiryActions.Rows.Add(drEnquiryActions);
                    }
                }

                //Session[SESSION_TBL] = tblEnquiryActions;
            });

            return tblEnquiryActions;
        }

        private void BindDataToGrid(DataTable dtActionDatas)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                //DataTable dataTable = (DataTable)Session[SESSION_TBL];
                gvEnquiryActions.DataSource = dtActionDatas;
                gvEnquiryActions.DataBind();

                //for (int i = 0; i < gvEnquiryActions.Rows.Count; i++)
                //{
                //    ImageButton edit = (ImageButton)gvEnquiryActions.Rows[i].Cells[7].FindControl("Image");
                //    edit.Enabled = false;
                //    gvEnquiryActions.AutoGenerateEditButton = false;
                //}

                if (gvEnquiryActions.Rows.Count > 0)
                {
                    lblEmptyText.Visible = false;
                }
                else
                {
                    lblEmptyText.Visible = true;
                }
            });
        }


        protected void gvEnquiryActions_OnDataBound(object sender, EventArgs e)
        {

            //ImageButton edit = (ImageButton)gvEnquiryActions.FindControl("Image");
            //edit.Visible = false;
            //edit.Enabled = false; //OR use this line
            //gvEnquiryActions.Columns[8].Visible = false;
        }

        protected void gvEnquiryActions_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.Header)
            {
                if (!canEdit)
                {
                    e.Row.Cells[11].Visible = false;
                    e.Row.Cells[12].Visible = true;
                }
                else
                {
                    e.Row.Cells[11].Visible = true;
                    e.Row.Cells[12].Visible = false;
                }

                if (!canDelete)
                {
                    e.Row.Cells[13].Visible = false;
                    e.Row.Cells[14].Visible = true;
                }
                else
                {
                    e.Row.Cells[13].Visible = true;
                    e.Row.Cells[14].Visible = false;
                }
            }


            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                e.Row.Cells[12].Enabled = false;
                e.Row.Cells[14].Enabled = false;
                if (!canEdit)
                {
                    e.Row.Cells[11].Visible = false;
                    e.Row.Cells[12].Visible = true;
                }
                else
                {
                    e.Row.Cells[11].Visible = true;
                    e.Row.Cells[12].Visible = false;
                }

                if (!canDelete)
                {
                    e.Row.Cells[13].Visible = false;
                    e.Row.Cells[14].Visible = true;
                }
                else
                {
                    e.Row.Cells[13].Visible = true;
                    e.Row.Cells[14].Visible = false;
                }
            }
        }

        protected void gvEnquiryActions_RowEditing(object sender, GridViewEditEventArgs e)
        {
            try
            {
                if (canEdit)
                {
                    divAppPage.Visible = true;
                    SPSecurity.RunWithElevatedPrivileges(delegate()
                    {
                        HiddenField hdnId = (HiddenField)gvEnquiryActions.Rows[e.NewEditIndex].FindControl("hdnid");
                        if (hdnId != null)
                        {
                            itmeID = Convert.ToInt32(hdnId.Value);
                            btnSave.Text = "Update";
                            BindDataToControls(itmeID);
                        }
                    });

                }
                else
                {
                    pnlAlert.Controls.Add(new LiteralControl("<script language='javascript'>alert('You do not have permission to edit this action!');</script>"));
                    //ClientScript.RegisterClientScriptBlock(GetType(), "Add Actions", "<script>alert('You do not have permission to edit this action!')</script>");
                }
            }
            catch (Exception ex)
            {
                ErrorMsgs = "iGRID_Ooredoo_SPCRM_My_Opportunities :: OppertunitiesActions" + " :: " + "Parent" + " :: " + "PageLoad";
                errMsg.GenerateExceptionLog(ErrorMsgs, ex.Message, "");
            }
        }

        protected void gvEnquiryActions_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                try
                {

                    // GridViewRow row = gvEnquiryActions.Rows[e.RowIndex];
                    HiddenField hdnId = (HiddenField)gvEnquiryActions.Rows[e.RowIndex].FindControl("hdnid");
                    if (hdnId != null)
                    {
                        deleteitemID = Convert.ToInt32(hdnId.Value);
                        //if (CkActionUser(deleteitemID))

                        if (canDelete)
                        {
                            var sb = new StringBuilder();
                            //Convert.ToInt32(gvEnquiryActions.Rows[e.RowIndex].Cells[0].Text);
                            sb.AppendFormat("var foo = window.confirm('Are you sure to delete ?');\n");
                            sb.Append("if (foo)\n");
                            sb.Append("__doPostBack('MyConfirmationPostBackEventTarget', foo);\n");
                            ClientScript.RegisterStartupScript(GetType(), "MyScriptKey", sb.ToString(), true);
                        }
                        else
                        {
                            pnlAlert.Controls.Add(new LiteralControl("<script language='javascript'>alert('You do not have permission to delete this action!');</script>"));
                            //ClientScript.RegisterClientScriptBlock(GetType(), "Add Actions", "<script>alert('You do not have permission to delete this action!')</script>");
                        }
                    }
                    //DeleteRecords(itemID);
                }
                catch (Exception ex)
                {
                    ErrorMsgs = "iGRID_Ooredoo_SPCRM_My_Opportunities :: OppertunitiesActions" + " :: " + "Parent" + " :: " + "gvEnquiryActions_RowDeleting";
                    errMsg.GenerateExceptionLog(ErrorMsgs, ex.Message, "");
                }
            });
        }

        private bool CkActionUser(int itemID)
        {
            bool actionUser;
            using (SPSite oSite = new SPSite(SPContext.Current.Site.Url))
            {
                using (SPWeb oWeb = oSite.OpenWeb())
                {
                    SPListItem listItem = oWeb.Lists.TryGetList("Action Details").GetItemById(itemID);

                    string actionBy = Convert.ToString(listItem["ActionBy"]);
                    SPFieldUserValue fldUser = new SPFieldUserValue(oWeb, actionBy);

                    if (fldUser.LookupValue.ToLower() == Convert.ToString(SPContext.Current.Web.CurrentUser).ToLower())
                        actionUser = true;
                    else
                        actionUser = false;
                }
            }
            return actionUser;
        }

        private void DeleteRecords(int itemID)
        {
            SPListItem oLstItem = SPContext.Current.Web.Lists.TryGetList("Action Details").GetItemById(itemID);
            oLstItem.Delete();
        }


        private void BindDataToControls(int itemID)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                SPList listEnquiries = SPContext.Current.Web.Lists.TryGetList("Action Details");
                SPQuery query = new SPQuery();
                query.Query = "<Where><Eq><FieldRef Name='ID' /><Value Type='Counter'>" + Convert.ToString(itemID) + "</Value></Eq></Where>";

                SPListItemCollection coll = listEnquiries.GetItems(query);
                SPListItem dr = coll[0];

                lblEnquiryIdShow.Text = Convert.ToString(dr["OpportunityID"]);
                lblEnquiryTitleShow.Text = GetEnquiryTitle(Convert.ToString(dr["OpportunityID"]));
                dtActStDate.ClearSelection();
                dtActStDate.SelectedDate = Convert.ToDateTime(dr["ActionStartDate"]);
                dtActEndDate.ClearSelection();
                dtActEndDate.SelectedDate = Convert.ToDateTime(dr["ActionEndDate"]);
                ddlActionTypes.Items.FindByText(Convert.ToString(dr["ActionType"])).Selected = true;
                txtRemarks.Text = Util.StripHTML(Convert.ToString(dr["Remarks"]));
            });
        }

        private void BindDataToControls(GridViewRow pRow)
        {
            //SPSecurity.RunWithElevatedPrivileges(delegate()
            //{
            //    txtPONo.Text = pRow.Cells[1].Text;
            //    //txtActionType.Text = pRow.Cells[2].Text;
            //    ddlActionTypes.SelectedValue = pRow.Cells[2].Text;
            //    dtcActionDate.SelectedDate = Convert.ToDateTime(pRow.Cells[3].Text);
            //    txtAmountPaid.Text = Util.StripHTML(pRow.Cells[4].Text);
            //    txtRemarks.Text = Util.StripHTML(pRow.Cells[5].Text);
            //});
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            SPListItem listItem = null;
            SPListItemCollection lstColl = null;
            string camlQry = "";
            SPQuery qry = null;

            if (dtActStDate.SelectedDate.Date >= strOppDate.Date)
            {
                lblEmptyText.Text = "";

                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    try
                    {
                        using (SPSite oSite = new SPSite(SPContext.Current.Site.Url))
                        {
                            using (SPWeb oWeb = oSite.OpenWeb())
                            {
                                SPList oList = oWeb.Lists.TryGetList("Action Details");
                                oWeb.AllowUnsafeUpdates = true;
                                if (oList != null)
                                {
                                    if (btnSave.Text != "Update")
                                    {
                                        qry = new SPQuery();

                                        //if (string.IsNullOrEmpty(txtRemarks.Text))
                                        camlQry = "<Where><And><Eq><FieldRef Name=\"Title\" /><Value Type=\"Text\">" + lblEnquiryTitleShow.Text + "</Value></Eq><And><Eq>" +
                                            "<FieldRef Name=\"OpportunityID\" /><Value Type=\"Text\">" + strEnquiryId + "</Value></Eq><And><Eq><FieldRef Name=\"ActionType\" />" +
                                            "<Value Type=\"Text\">" + ActionType + "</Value></Eq><And><Eq><FieldRef Name=\"ActionStartDate\" />" +
                                            "<Value IncludeTimeValue=\"TRUE\" Type=\"DateTime\">" + ToSPDateTime(Convert.ToString(dtActStDate.SelectedDate)) + "</Value></Eq><Eq><FieldRef Name=\"ActionEndDate\" />" +
                                            "<Value IncludeTimeValue=\"TRUE\" Type=\"DateTime\">" + ToSPDateTime(Convert.ToString(dtActEndDate.SelectedDate)) + "</Value></Eq></And></And></And></And></Where>";


                                        qry.Query = camlQry;
                                        lstColl = GetListItemCollection(oList, qry);
                                        if (lstColl != null)
                                        {
                                            if (lstColl.Count == 0)
                                            {
                                                listItem = oList.Items.Add();
                                                listItem["Title"] = lblEnquiryTitleShow.Text; //lblEnquiryIdShow.Text;
                                                listItem["OpportunityID"] = lblEnquiryIdShow.Text; //lblEnquiryIdShow.Text;
                                                //listItem["ActionType"] = ddlActionTypes.SelectedValue;
                                                listItem["ActionType"] = ActionType;//ddlActionTypes.SelectedItem.Text; 
                                                //new SPFieldLookupValue(Convert.ToString(ddlActionTypes.SelectedValue + ";#" + ddlActionTypes.SelectedItem.Text));
                                                listItem["ActionStartDate"] = dtActStDate.SelectedDate;
                                                listItem["ActionEndDate"] = dtActEndDate.SelectedDate;
                                                listItem["Remarks"] = txtRemarks.Text;
                                                listItem["Status"] = "Active";
                                                listItem["ActionBy"] = SPContext.Current.Web.CurrentUser;
                                                listItem["ActionModifiedBy"] = SPContext.Current.Web.CurrentUser;
                                                listItem.Update();
                                                pnlAlert.Controls.Add(new LiteralControl("<script language='javascript'>alert('Action saved successfully!');</script>"));
                                                //ClientScript.RegisterClientScriptBlock(GetType(), "Add Actions", "<script>alert('Action saved successfully')</script>");
                                            }
                                            else
                                            {
                                                pnlAlert.Controls.Add(new LiteralControl("<script language='javascript'>alert('Duplicate entry not allowed');</script>"));
                                                //ClientScript.RegisterClientScriptBlock(GetType(), "Add Actions", "<script>alert('Duplicate entry not allowed')</script>");
                                            }
                                        }
                                    }
                                    else
                                    {
                                        if (canEdit)
                                        {
                                            listItem = oList.GetItemById(itmeID);
                                            listItem["ActionType"] = ActionType;
                                            listItem["ActionStartDate"] = dtActStDate.SelectedDate;
                                            listItem["ActionEndDate"] = dtActEndDate.SelectedDate;
                                            listItem["ActionModifiedBy"] = SPContext.Current.Web.CurrentUser;
                                            listItem["Remarks"] = txtRemarks.Text;
                                            btnSave.Text = "Save";
                                            listItem.Update();
                                            pnlAlert.Controls.Add(new LiteralControl("<script language='javascript'>alert('Action updated successfully');</script>"));
                                            //ClientScript.RegisterClientScriptBlock(GetType(), "Add Actions", "<script>alert('Action updated successfully')</script>");
                                            if (canAdd)
                                                divAppPage.Visible = true;
                                            else
                                                divAppPage.Visible = false;
                                        }
                                    }

                                    qry = new SPQuery();
                                    camlQry = "<Where><Eq><FieldRef Name=\"OpportunityID\" /><Value Type=\"Text\">" + strEnquiryId + "</Value>" +
                                        "</Eq></Where><OrderBy><FieldRef Name=\"ActionDate\" Ascending=\"False\" /></OrderBy>";
                                    qry.Query = camlQry;

                                    SPListItemCollection lstDats;
                                    lstDats = GetListItemCollection(oList, qry);
                                    if (lstDats != null)
                                        BindDataToGrid(CreateEnquiryActionsDataForGrid(lstDats));
                                    ClearControls();
                                }
                                oWeb.AllowUnsafeUpdates = false;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        ErrorMsgs = "iGRID_Ooredoo_SPCRM_My_Opportunities :: OppertunitiesActions" + " :: " + "Parent" + " :: " + "Save Click";
                        errMsg.GenerateExceptionLog(ErrorMsgs, ex.Message, "");
                    }
                });
            }
            else
            {
                lblEmptyText.Visible = true;
                lblEmptyText.Text = "Selected Date should be less than Opportunity Date"; lblEmptyText.ForeColor = System.Drawing.Color.Red;
            }
            dtActStDate.SelectedDate = DateTime.Today;
            dtActEndDate.SelectedDate = DateTime.Today;
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            Response.Write("<script language='javascript'>document.location.href = '/sitepages/redirect.aspx'</script>");
        }

        private static String ToSPDate(String strDt)
        {
            if (strDt == String.Empty)
                return strDt;
            else
                return (Convert.ToDateTime(strDt)).ToString("yyyy-MM-dd");
        }

        private static String ToSPDateTime(String strDt)
        {
            if (strDt == String.Empty)
                return strDt;
            else
                return (Convert.ToDateTime(strDt)).ToString("yyyy-MM-ddTHH:mm:ssZ");
        }

        private SPListItemCollection GetListItemCollection(SPList oList, SPQuery qry)
        {
            SPListItemCollection list = null;
            try
            {
                list = oList.GetItems(qry);
            }
            catch (Exception)
            {
                list = null;
            }
            return list;

        }

        //protected void btnCancel_Click(object sender, EventArgs e)
        //{
        //    ClearControls();
        //}

        private void ClearControls()
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                //txtPONo.Text = String.Empty;
                //txtActionType.Text = String.Empty;
                ddlActionTypes.ClearSelection(); //ddlActionTypes.SelectedValue = "";
                dtActStDate.SelectedDate = DateTime.Now;
                txtRemarks.Text = String.Empty;
            });
        }

        protected void gvEnquiryActions_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                gvEnquiryActions.PageIndex = e.NewPageIndex;
                //tblEnquiryActions = GetEnquiryActionsTable();
                BindDataToGrid(tblEnquiryActions);
            });
        }
    }

}
